package com.dibang.app.mvp.util;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.util.Log;

import java.util.ArrayList;

/**
 * Created by wxl on 2019/8/6.
 */

public class Voice {

    private static SpeechRecognizer mSpeechRecognizer;


    /**
     * 开始录制
     */
    public static void startRecordVoice(Context context){
        Intent recognitionIntent=new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        recognitionIntent.putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS,true);
        recognitionIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE,"zh-CN");
        mSpeechRecognizer=SpeechRecognizer.createSpeechRecognizer(context);
        mSpeechRecognizer.setRecognitionListener(new VoiceRecognitionListener());
        mSpeechRecognizer.startListening(recognitionIntent);
    }


    public static void onDestory(){
        if(mSpeechRecognizer != null){
            mSpeechRecognizer.destroy();
        }
    }


    private static class VoiceRecognitionListener implements RecognitionListener {

        @Override
        public void onReadyForSpeech(Bundle params) {

        }

        @Override
        public void onBeginningOfSpeech() {

        }

        @Override
        public void onRmsChanged(float rmsdB) {

        }

        @Override
        public void onBufferReceived(byte[] buffer) {

        }

        @Override
        public void onEndOfSpeech() {

        }

        @Override
        public void onError(int error) {

        }

        @Override
        public void onResults(Bundle results) {
            ArrayList<String> partialResults=results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
            if(partialResults!=null && partialResults.size()>0) {
                String bestResult = partialResults.get(0);
                Log.d("voice","onResults = "+bestResult);
            }
        }

        @Override
        public void onPartialResults(Bundle partialResults) {
            ArrayList<String> results=partialResults.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
            if(results!=null && results.size()>0){
                String bestResult=results.get(0);
                Log.d("voice","onPartialResults = "+bestResult);
            }
        }

        @Override
        public void onEvent(int eventType, Bundle params) {

        }
    }






}
